package com.backend.system.common;

import cn.dev33.satoken.stp.StpUtil;
import com.backend.system.common.annotation.WithoutLogin;
import com.backend.system.common.enums.ErrorEnum;
import com.backend.system.dao.entity.User;
import com.backend.system.service.IUserService;
import com.backend.system.util.ExecuteExpressUtil;
import com.backend.system.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 请求响应拦截器
 *
 * @version v1.0
 * @author: backend-manage
 * @date: 2024年03月20日 23时31分
 */
@Slf4j
public class RequestHolderHandlerInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod action) {
            WithoutLogin withoutLogin = action.getMethodAnnotation(WithoutLogin.class);
            if (withoutLogin != null) {
                return true;
            }
        }

        RequestHolder.remove();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        // 加上校验放行
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return true;
        }

        // 设置用户信息，从请求头中获取
        setUserInfo(request);
        setLogId(request);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }

    private void setUserInfo(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader(StringConstant.AUTHORIZATION);
        // 从请求头中获取角色
        String roleId = request.getHeader(StringConstant.ROLE_ID);

        if (StringUtil.isBlank(token) || StringUtil.isBlank(roleId)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (StringConstant.SA_TOKEN.equals(cookie.getName())) {
                        token = cookie.getValue();
                        continue;
                    }
                    if (StringConstant.ROLE_ID.equals(cookie.getName())) {
                        roleId = cookie.getValue();
                    }
                }
            }
        }

        if (StringUtil.isNotBlank(token) && token.startsWith(StringConstant.TOKEN_PREFIX)) {
            token = token.replaceFirst(StringConstant.TOKEN_PREFIX, StringConstant.EMPTY_STR);
        }
        final String finalToken = token;
        final String finalRoleId = roleId;

        // 用户登录拦截
        Object loginId = StpUtil.getLoginIdByToken(finalToken);
        if (Objects.isNull(loginId)) {
            throw new CustomException(ErrorEnum.UN_LOGIN_ERROR);
        }

        User user = userService.getById(Long.valueOf(loginId.toString()));
        RequestHeaderUserInfo userInfo = new RequestHeaderUserInfo();
        ExecuteExpressUtil.setIfPresent(StringUtils.hasLength(finalToken), () -> userInfo.setToken(finalToken));
        ExecuteExpressUtil.setIfPresent(user != null, () -> {
            userInfo.setUsername(user.getUsername());
            userInfo.setLoginAccount(user.getLoginAccount());
        });
        userInfo.setLoginId(Long.valueOf(loginId.toString()));
        ExecuteExpressUtil.setIfPresent(StringUtils.hasLength(finalRoleId), () -> userInfo.setRoleId(Long.valueOf(finalRoleId)));

        RequestHolder.REQUEST_HEADER_USER_INFO_THREAD_LOCAL.set(userInfo);
    }

    private void setLogId(HttpServletRequest request) {
        // 从请求头中获取logId
        String logId = request.getHeader(StringConstant.LOG_ID);
        if (StringUtils.hasLength(logId)) {
            LogId.put(logId);
            return;
        }
        LogId.put(StringUtil.uuid());
    }
}
